package com.llmcu.configure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 尝试性地实现，在垃圾清理开始前
 *
 * @author liuling
 * @date 2024-10-22 15:00
 */
@Component
@Slf4j
public class GCNotificationListener {

    @PostConstruct
    public void register() {
        log.info("GCNotificationListener register successfully================================");
        List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean gc : gcBeans) {
            NotificationEmitter emitter = (NotificationEmitter) gc;
            emitter.addNotificationListener(new NotificationListener() {
                @Override
                public void handleNotification(Notification notification, Object handback) {
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String formattedDateTime = now.format(formatter);
                    log.info("start garbage collect:[{}],time:[{}]",gc.getName(),formattedDateTime);
                }
            }, null, null);
        }
    }

}
